//
//  Request.m
//  Request
//
//  Created by 袁灿 on 2017/11/24.
//  Copyright © 2017年 火山. All rights reserved.
//

#define BASE_REQUEST    @"http://hb.mkejt.com/"

#import "Request.h"

@implementation Request

+ (instancetype)sharedInstance
{
    static Request *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[Request alloc] init];
    });
    return _sharedInstance;
}

- (NSDictionary *)apiPost:(NSString *)url param:(NSMutableDictionary *)param
{
    NSString *result = @"";
    for (NSInteger i=0; i<param.count; i++) {
        NSString *key = param.allKeys[i];
        NSString *value = param.allValues[i];
        if (param.count > 1) {
            result = [NSString stringWithFormat:@"%@&%@=%@",result, key, value];
        } else {
            result = [NSString stringWithFormat:@"%@=%@", key, value];
        }
    }
    
    url = [NSString stringWithFormat:@"%@%@",BASE_REQUEST,url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval = 5.0;
    request.HTTPMethod = @"POST";
    request.HTTPBody = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *resData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    return [NSJSONSerialization JSONObjectWithData:resData options:0 error:NULL];
    
}

-(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = @"";
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

@end
